<template>
  <div class="main-table-content">

    <div class="fx" style="margin-left: 16px;padding-top: 16px">
      <el-button plain @click="treeExpandAll">展开/关闭</el-button>
    </div>

    <div class="fx" style="margin-left: 16px;margin-top: 12px">

      <div>

        <el-input v-model="option.filterTreeText" placeholder="输入内容自动搜索" style="width: 392px;"
                  suffix-icon="Search"/>

        <!--级联选项开关-->
        <div style="margin-top: 4px;margin-bottom: 2px">
          <el-switch
              v-model="option.treeCheckStrictly"
              class="ml-2"
              inline-prompt
              style="--el-switch-on-color: #ff4949;--el-switch-off-color: #13ce66"
              active-text="已关闭级联"
              inactive-text="已开启级联"
          />
        </div>

        <el-tree ref="orgTree"
                 node-key="id"
                 v-if="option.showOrgTree"
                 :props="{ value: 'id', label: 'name', children: 'children' }"
                 :data="option.orgDataLeft"
                 :default-expand-all="option.expandAll"
                 :filter-node-method="filterTreeNode"
                 @node-click="nodeClick"
                 :check-strictly="option.treeCheckStrictly"
                 show-checkbox style="width: 360px;" highlight-current>

          <template #default="{ node, data }">
            <div>{{ node.label }}
            </div>
          </template>

        </el-tree>
      </div>

      <el-form class="fx1" ref="formDataRef" :model="formData" :rules="formRules" label-width="100"
               style="margin-left: 24px">

        <el-form-item label="上级菜单" prop="pid">
          <el-tree-select
              disabled
              style="width: 500px"
              v-model="formData.pid"
              :data="option.orgData"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              placeholder="默认根节点"
              @node-click="treeSelect"
              check-strictly
          />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <div v-if="formData.type=='D'" class="inline SD bold">[目录]</div>
          <div v-if="formData.type=='M'" class="inline SM bold">[菜单]</div>
          <div v-if="formData.type=='F'" class="inline SFF bold">[功能]</div>
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input readonly v-model="formData.name" placeholder="请输入名称" style="width: 500px"/>
        </el-form-item>

        <el-form-item v-if="formData.type=='M'" label="路由地址" prop="routePath">
          <el-input readonly v-model="formData.routePath" placeholder="请输入访问地址" style="width: 500px"/>
        </el-form-item>

        <el-form-item v-if="formData.type=='M'" label="文件地址" prop="filePath">
          <el-input readonly v-model="formData.filePath" placeholder="请输入文件地址" style="width: 500px"/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number readonly v-model="formData.sort" controls-position="right" :min="0" style="width: 200px"/>
        </el-form-item>

        <el-form-item label="数据权限" prop="res">
          <el-input readonly v-model="formData.res" maxlength="2000"
                    placeholder="请输入拥有的数据权限（逗号分隔，禁止输入换行符）"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" style="width: 500px" type="textarea"/>
        </el-form-item>

        <el-form-item label="排除权限" prop="resExclude">
          <el-input readonly v-model="formData.resExclude" maxlength="2000"
                    placeholder="请输入排除的数据权限（逗号分隔，禁止输入换行符）"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" style="width: 500px" type="textarea"/>
        </el-form-item>

      </el-form>

    </div>

  </div>
</template>

<script setup>
import {getCurrentInstance, nextTick, onMounted, ref, watch} from "vue";
import {apiUserHasOrg} from "@/api/system";
import {parseTree} from "@/common/utils/kit";

const {proxy} = getCurrentInstance();

const props = defineProps({
  defaultChecked: {
    default: []
  },
  //默认值为 false. 如果参数为 true, 返回值包含半选中节点数据
  includeHalfChecked: {
    default: false,
  },
})

//暴露内部对象给外部使用
defineExpose({
  returnCheckData
})
//生命通知上层的事件
const emit = defineEmits(['callBack'])

let optionKey = {
  treeCheckStrictly: false,//默认关闭级联
  dialogTitle: "",
  openDialog: false,
  loading: false,
  orgDataLeft: [],
  orgData: [],
  expandAll: false,
  showOrgTree: true,
  disabledD: false,
  disabledM: false,
  disabledF: false,
  filterTreeText: '',
}
let formKey = {
  pid: "",
  level: 0,
  name: "",
  routePath: "",
  filePath: "",
  type: "D",
  sort: 100,
  res: "",
  resExclude: "",
}

const formRules = ref({
  pid: [{required: true, message: "不能为空", trigger: "change"}],
  type: [{required: true, message: "不能为空", trigger: "change"}],
  sort: [{required: true, message: "不能为空", trigger: "blur"}],
  name: [{required: true, message: "不能为空", trigger: "blur"}],
  routePath: [{required: true, message: "不能为空", trigger: "blur"}],
  filePath: [{required: true, message: "不能为空", trigger: "blur"}],
  menuName: [{required: true, message: "不能为空", trigger: "blur"}],
  orderNum: [{required: true, message: "不能为空", trigger: "blur"}],
  path: [{required: true, message: "不能为空", trigger: "blur"}]
});
const option = ref(optionKey);
const formData = ref(formKey);

//页面加载完成回调
onMounted(() => {
  ////console.log("props.defaultChecked ", props.defaultChecked)
  proxy.$refs["orgTree"].setCheckedKeys(props.defaultChecked);
  selectAllMenu()
})

//上级目录下拉选
function treeSelect(value) {
  let level = 0;
  if (value.level) {
    level = value.level * 1 + 1;
  }
  formData.value.level = level
  ////console.log("value.level ", value.level)
  ////console.log(" formData.value.level ", formData.value.level)
}

function nodeClick(row) {
  formData.value = JSON.parse(JSON.stringify(row));
}

watch(option.value, (val) => {
  if (proxy.$refs["orgTree"]) {
    proxy.$refs["orgTree"].filter(val.filterTreeText)
  }
})

function filterTreeNode(value, data) {
  if (!value) return true
  return data.name.includes(value)
}

async function selectAllMenu() {
  let res = await apiUserHasOrg()
  // //console.log(res)
  option.value.orgDataLeft = parseTree(res.data);
  option.value.orgData = parseTree(res.data);
  option.value.orgData.unshift({id: "0", name: '根节点'})
  // //console.log(option.value.orgData)
}

// getCheckedNodes(leafOnly, includeHalfChecked)
// 接收两个布尔类型参数:
// 1. 默认值为 false. 若参数为 true, 它将返回当前选中节点的子节点
// 2. 默认值为 false. 如果参数为 true, 返回值包含半选中节点数据
function returnCheckData() {
  let checkedNodes = proxy.$refs["orgTree"].getCheckedNodes(false, props.includeHalfChecked);
  return emit('callBack', {checkedNodes})
}

function treeExpandAll() {
  let checkedKeys = proxy.$refs["orgTree"].getCheckedKeys();
  option.value.showOrgTree = false;
  option.value.expandAll = !option.value.expandAll
  nextTick(() => {
    option.value.showOrgTree = true;

    nextTick(() => {
      proxy.$refs["orgTree"].setCheckedKeys(checkedKeys);
    });

  });
}

</script>

<style scoped lang="less">

.SSZ {
  zoom: 0.8;
}

.SD {
  font-size: 15px;
  color: #c57d11;
  //border: 1px dashed #c57d11;
}

.SM {
  font-size: 15px;
  color: #109eda;
  //border: 1px dashed #109eda;
}

.SFF {
  font-size: 15px;
  color: #7ecb2d;
  //border: 1px dashed #109eda;
}

.SF {
  color: #7ecb2d;
  font-size: 13px;
  border: 1px solid #57d753;
  border-radius: 99px;
  padding-left: 4px;
  padding-right: 4px;
}
</style>